package com.studentstreet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.studentstreet.component.LwtAlertController;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.tools.PreferenceTools;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.Preference;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;

/**
 * @author likebamboo
 * 
 */
public class MoreActivity extends Activity {
	// 搜索按钮
	private Button searchBt = null;
	// 与搜索类别相关、
	// 搜索类别popupWindow
	private PopupWindow classPop = null;
	// 搜索类别按钮
	private Button searchClassBt = null;
	// 搜索类别列表
	private ListView classPopList = null;
	// 搜索类别列表中的数据
	private List<Map<String, Object>> classData = null;
	// 搜索类别最终数据（用于传递到下个Activity）
	private String classValue = "";
	// 搜索信息描述,用于下个Activity显示搜索条件描述
	private String search_info = "";
	private String search_class_info = "";

	// EditText,用于输入关键字
	private EditText searchEdit = null;

	// 与搜索价格有关
	// 搜索价格popupWindow
	private PopupWindow pricePop = null;
	// 搜索价格按钮
	private Button searchPriceBt = null;
	// 价格列表
	private ListView pricePopList = null;
	// 价格列表数据
	private List<Map<String, Object>> priceData = null;
	// 价格的最终数据
	private String priceValue = "";

	// GridView相关
	private GridView gridViewMore = null;
	// 用于填充gridView的数据
	private List<Map<String, Object>> gridviewData = null;

	// OEM ++ 3013-04-05 智能推荐
	// 用户名
	private String userName = null;

	// OEM--

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.more);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);

		search_class_info = getStrArr(R.array.search_class_info)[0];

		// 初始化与搜索类别有关的控件
		initSearchClass();

		// 初始化输入框
		searchEdit = (EditText) findViewById(R.id.more_search_edit);

		// 与搜索价格有关
		initSearchPrice();

		// 搜索按钮
		searchBt = (Button) findViewById(R.id.search_bt);
		searchBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 不允许不输入及单纯输入空格
				if ("".equals(searchEdit.getText().toString().trim())) {
					searchEdit.setError(getStr(R.string.search_input_error));
					return;
				}
				// 启动搜索结果界面
				Intent intent = new Intent(MoreActivity.this,
						SearchResultActivity.class);
				intent.putExtra("class", classValue);
				intent.putExtra("price", priceValue);
				intent.putExtra("key", searchEdit.getText().toString());
				intent.putExtra("search_info", getSearchInfo());
				startActivity(intent);
			}
		});

		initGridView();
	}

	// 初始化与搜索类别有关的数据
	private void initSearchClass() {
		// 与搜索类别有关
		// 初始化类别最初的值，为 all
		classValue = getStrArr(R.array.search_class_value)[0];
		// 搜索类别按钮
		searchClassBt = (Button) findViewById(R.id.more_search_class);
		// 搜索类别ListView
		classPopList = new ListView(this);
		// 搜索类别List
		classData = new ArrayList<Map<String, Object>>();
		// 填出搜索类别List，为Adapter做准备
		String[] more_search_class = getStrArr(R.array.search_class);
		for (int i = 0; i < more_search_class.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("class", more_search_class[i]);
			classData.add(map);
		}

		// 建立类别适配器
		SimpleAdapter classAdapter = new SimpleAdapter(this, classData,
				R.layout.search_pop, new String[] { "class" },
				new int[] { R.id.search_class });

		// 为ListView设置适配器
		classPopList.setAdapter(classAdapter);
		// 取消ListView 的分割线
		classPopList.setDivider(null);
		// 设置ListView的 Item的单击事件
		classPopList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				// 设置搜索类别按钮上的文字
				searchClassBt.setText((String) classData.get(position).get(
						"class"));

				// 改变搜索类别的最终值
				classValue = getStrArr(R.array.search_class_value)[position];
				// 改变搜索信息描述
				search_class_info = getStrArr(R.array.search_class_info)[position];

				// 让popupWindow消失
				if (classPop != null)
					classPop.dismiss();
			}
		});
		// 点击按钮时，显示PopupWindow
		searchClassBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (classPop == null) {
					classPop = new PopupWindow(classPopList, v.getWidth(),
							LayoutParams.WRAP_CONTENT);
				}
				// 显示popupWindow
				showPop(classPop, v);
			}

		});

	}

	// 初始化与搜索价格相关的控件
	private void initSearchPrice() {
		// 初始化价格最初值 为 >0
		priceValue = getStrArr(R.array.search_price_value)[0];
		// 初始化价格按钮
		searchPriceBt = (Button) findViewById(R.id.more_search_price);
		// 初始化价格ListView
		pricePopList = new ListView(this);
		// 初始化价格List数据
		priceData = new ArrayList<Map<String, Object>>();
		// 填充List为Adapter做准备
		String[] more_search_price = getStrArr(R.array.search_price);
		for (int i = 0; i < more_search_price.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("price", more_search_price[i]);
			priceData.add(map);
		}

		// 建立一个Adapter
		SimpleAdapter priceAdapter = new SimpleAdapter(this, priceData,
				R.layout.search_pop, new String[] { "price" },
				new int[] { R.id.search_class });

		// 为ListView 设置Adapter
		pricePopList.setAdapter(priceAdapter);
		// 取消ListView中间的分割线
		pricePopList.setDivider(null);
		// 设置ListView 的Item的单击事件
		pricePopList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				searchPriceBt.setText((String) priceData.get(position).get(
						"price"));
				priceValue = getStrArr(R.array.search_price_value)[position];
				pricePop.dismiss();
			}
		});
		// 单击价格搜索框时，显示popupWindow
		searchPriceBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pricePop == null) {
					pricePop = new PopupWindow(pricePopList, v.getWidth(),
							LayoutParams.WRAP_CONTENT);
				}
				showPop(pricePop, v);
			}
		});
	}

	private void initGridView() {
		// gridView中的数据
		gridviewData = new ArrayList<Map<String, Object>>();
		// 图片资源
		int[] more_menu_img = { R.drawable.more_menu1, R.drawable.more_menu2,
				R.drawable.more_menu3, R.drawable.more_menu4,
				R.drawable.more_menu5 };
		// 字符串资源
		String[] more_menu_text = { getStr(R.string.more_menu1),
				getStr(R.string.more_menu2), getStr(R.string.more_menu3),
				getStr(R.string.more_menu4), getStr(R.string.more_menu5) };
		// 填充gridViewData
		for (int i = 0; i < more_menu_img.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("img", more_menu_img[i]);
			map.put("text", more_menu_text[i]);
			gridviewData.add(map);
		}

		// 初始化GridView控件
		gridViewMore = (GridView) findViewById(R.id.more_gridview);
		// 创建适配器
		SimpleAdapter gridAadapter = new SimpleAdapter(this, gridviewData,
				R.layout.more_menu, new String[] { "img", "text" }, new int[] {
						R.id.menu_image, R.id.menu_text });
		// 为Gridview设置适配器
		gridViewMore.setAdapter(gridAadapter);

		gridViewMore.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent();
				switch (arg2) {
				// 随便逛逛
				case 0:
					intent.setClass(getApplication(), HangOutActivity.class);
					intent.putExtra("action", "get_rand_goods");
					intent.putExtra("userName", userName);
					startActivity(intent);
					break;
				// 最新商品
				case 1:
					intent.setClass(getApplication(), HangOutActivity.class);
					intent.putExtra("action", "get_recent_goods");
					intent.putExtra("userName", userName);
					startActivity(intent);
					break;
				// 为我推荐
				case 2:
					intent.setClass(getApplication(), HangOutActivity.class);
					intent.putExtra("action", "get_recommand_goods");
					PreferenceTools pref = new PreferenceTools(
							getApplicationContext());
					if (!pref.isLogin()) {
						Toast.makeText(getApplicationContext(),
								getStr(R.string.have_no_login),
								Toast.LENGTH_SHORT).show();
						break;
					}
					userName = pref.getUserName();
					intent.putExtra("userName", userName);
					startActivity(intent);
					break;

				// 更新
				case 3:
					showDialog();
					break;
				// 关于我们
				case 4:
					intent.setClass(getApplication(), AboutUsActivity.class);
					startActivity(intent);
					break;

				default:
					break;
				}
			}
		});

	}

	private void showDialog() {
		LwtAlertDialog.Builder builder = new LwtAlertDialog.Builder(this);
		builder.setTitle(getString(R.string.update_title))
				.setMessage(R.string.update_message)
				.setPositiveButton(R.string.sure,
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		Dialog dialog = builder.create();
		dialog.show();
	}

	// 显示PopupWindow
	private void showPop(PopupWindow pop, View byView) {
		pop.setWidth(byView.getWidth());
		// 使其聚集
		pop.setFocusable(true);
		// 设置允许在外点击消失
		pop.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
		pop.setBackgroundDrawable(new BitmapDrawable());

		pop.showAsDropDown(byView);
	}

	// 搜索信息描述
	private String getSearchInfo() {
		search_info = search_class_info + "<font color ='red'><strong>"
				+ searchEdit.getText().toString() + "</strong></font> ";
		if (!priceValue.equals(getStrArr(R.array.search_class_value)[0])) {
			search_info += "," + getStr(R.string.search_price)
					+ "<font color ='red'><strong>"
					+ searchPriceBt.getText().toString() + "</strong></font>"
					+ getStr(R.string.search_info_late);
		}
		return search_info;
	}

	// 工具方法，获得字符串
	private String getStr(int resId) {
		return getResources().getString(resId);
	}

	// 工具方法，获得字符串数组
	private String[] getStrArr(int resId) {
		return getResources().getStringArray(resId);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApp.getInstance().exit(this);
		}
		return super.onKeyDown(keyCode, event);
	}
}
